import React, { useState, useEffect, useRef } from 'react'
import '../static/less/collect.less'
import { detail } from '../api/index'
import { Link } from 'react-router-dom';
export default function Collect() {
  let [collectList, setCollectList] = useState([]);
  // let [list, setList] = useState([]);
  let list = useRef([]);

  const listFn = () => {
    let v = localStorage.getItem("idList");
    // console.log(v);
    v = JSON.parse(v);
    list = v;
    // setList(v);
    // console.log(111,list);
  }

  const cListFn = async () => {
    // console.log(222,list);
    let l = [];
    for (let i = 0; i < list?.length; i++) {
      await detail({ id: list[i] }).then(
        content => {
          let { code, data } = content;
          if (code == 200) {
            let d = data;
            l.push(d);
          }
        }
      )
    }
    // console.log(333,l);
    setCollectList(l);
  }

  const removeFn = (i)=>{
    listFn();
    let l = [];
    // console.log(444,list);
    for(let j=0;j<list.length;j++){
      // console.log(j);
      if(j != i){
        // console.log(list[j]);
        l.push(list[j]);
      }
    }
    // console.log(l);
    localStorage.setItem("idList",JSON.stringify(l));
    listFn();
    cListFn();
  }

  // 初始化 
  useEffect(() => {
    listFn();
    cListFn();
  }, [list])

  return (
    <div className='collect'>
      <div className='top'>
        <h2 className='top-title'>书架</h2>
      </div>
      <div className='bottom' style={{display: collectList?.length == 0 ? 'block' :'none'}}>
        <p className='null'>书架暂时为空~~~</p>
      </div>
      <div className="bottom" style={{display: collectList?.length == 0 ? 'none' :'block'}}>
        {
          collectList.map((item, i) => {
            return (
              <div className="box" key={i}>
                <div className="left">
                  <Link to={`/detail?id=${item.id}`}>
                    <img src={item.pic} alt="" />
                  </Link>
                </div>
                <div className="right">
                  <h3 className='title'>{item.title}</h3>
                  <button className='btn' onClick={()=>{
                    removeFn(i);
                  }}>删除</button>
                  <p className='text'>{item.info}</p>
                  <div className='tag'>
                    {
                      item.tag.split(" ").map((itemm, j) => {
                        return (
                          <span key={j}>{itemm}</span>
                        )
                      })
                    }
                  </div>
                  <div className='numLook'>
                    {
                      (item.num_look / 10000).toFixed(2) + '万观看'
                    }
                  </div>
                  <div className='newZJ'>最新章节：{item.firstchapterid}话</div>
                </div>
              </div>
            )
          })
        }
      </div>
    </div>
  )
}
